package com.ly.web.controller.king;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.heart.domain.KingBaseRateEntity;
import com.ly.heart.domain.KingOrgEntity;
import com.ly.heart.domain.king.BaseChildBo;
import com.ly.heart.domain.king.base.BaseModelBo;
import com.ly.heart.domain.king.base.RateBo;
import com.ly.heart.domain.request.KingBaseRequest;
import com.ly.heart.domain.response.KingBaseResponse;
import com.ly.heart.domain.response.KingBaseResponseError;
import com.ly.heart.domain.response.KingBaseResponseSuccessEntity;
import com.ly.heart.service.IKingBaseRateService;
import com.ly.heart.service.IKingOrgService;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.heart.util.KingCommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 0:20 2024-07-04
 * @return
 */
@Api (value = "RateRemote", tags = "推基础数据-汇率体系")
@RestController
@RequestMapping ("/heart/RateRemote")
@Slf4j
public class RateRemote {

    @Resource
    private IKingBaseRateService iKingBaseRateService;
    @Resource
    private IKingOrgService iKingOrgService;

    @ApiOperation ("同步拉取金蝶汇率列表")
    @RequestMapping ("pull")
    public AjaxResult queryList () throws Exception {
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity :: getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        String jsonData = "{\"FormId\":\"" + KingConstUtil.BD_Rate + "\",\"FieldKeys\":\"FRateID,FExchangeRate,FReverseExRate,FRATETYPEID.FNumber,FCyForID.FNumber,FCyToID.FNumber\",\"FilterString\":[],\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
        List<List<Object>> lists = client.executeBillQuery ( jsonData );
        for ( int i = 0; i < lists.size (); i++ ) {
            List<Object> objects = lists.get ( i );
            log.info ( "-->{}", objects );
            KingBaseRateEntity rateEntity = iKingBaseRateService.getOne ( new QueryWrapper<KingBaseRateEntity> ().eq ( "rate_king_id", String.valueOf ( objects.get ( 0 ) ) ) );
            if ( rateEntity == null ) {
                rateEntity = new KingBaseRateEntity ();
                rateEntity.setRateKingId ( String.valueOf ( objects.get ( 0 ) ) );
                rateEntity.setDirectRate ( String.valueOf ( objects.get ( 1 ) ) );
                rateEntity.setIndirectRate ( String.valueOf ( objects.get ( 2 ) ) );
                rateEntity.setRateType ( String.valueOf ( objects.get ( 3 ) ) );
                rateEntity.setSourceCurrency ( String.valueOf ( objects.get ( 4 ) ) );
                rateEntity.setTargetCurrency ( String.valueOf ( objects.get ( 5 ) ) );
                rateEntity.setIsSend ( KingConstUtil.KING_DATA_IS_SEND_YES );
                iKingBaseRateService.insertKingBaseRateEntity ( rateEntity );
            }
        }
        return AjaxResult.success ();
    }

    /**
     * ERP审核业务时调用该方法
     * 汇率体系在金蝶新增后拉取，不能推送，没有Code无法关联！！！！！！！！！！！！！！！！！！！！！！
     * @return
     */
    //@RequestMapping ("push")
    public AjaxResult push () throws Exception {
        K3CloudApi client = new K3CloudApi ();
        //1.获取所有数据
        List<KingBaseRateEntity> list = iKingBaseRateService.list ( new QueryWrapper<KingBaseRateEntity> ().
                                                                            //eq ( "dept_id", CurrentUserUtil.getCompanyId () ).
                                                                                    eq ( "is_send", KingConstUtil.KING_DATA_IS_SEND_NO ) );
        if ( CollectionUtils.isEmpty ( list ) ) {
            return AjaxResult.error ( "暂无新数据可推！" );
        }
        batchSave ( list, client );
        submit ( list, client );
        audit ( list, client );
        return AjaxResult.success ( "推送汇率体系成功。" );
    }


    /**
     * 保存币别
     */
    private void batchSave (List<KingBaseRateEntity> list, K3CloudApi client) throws Exception {
        KingBaseRequest request = new KingBaseRequest ();
        List<BaseModelBo> bos = new ArrayList<> ();
        list.forEach ( rate -> {
            RateBo bo = new RateBo ();
            //bo.setFRateID ( rate.getRateKingId () );
            bo.setFExchangeRate ( rate.getDirectRate () );
            bo.setFReverseExRate ( rate.getIndirectRate () );
            BaseChildBo childBo = new BaseChildBo ();
            //原币
            childBo.setFNumber ( rate.getSourceCurrency () );
            bo.setFCyForID ( childBo );
            //目标币
            childBo = new BaseChildBo ();
            childBo.setFNumber ( rate.getTargetCurrency () );
            bo.setFCyToID ( childBo );
            //汇率类型
            childBo = new BaseChildBo ();
            childBo.setFNumber ( rate.getRateType () );
            bo.setFRATETYPEID ( childBo );
            bos.add ( bo );
        } );
        request.setModel ( bos );
        String s = JSONObject.toJSONString ( request );
        String resultJson = client.batchSave ( KingConstUtil.BD_Rate, s );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //添加成功，进行提交
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "汇率体系-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 推送成功", sb );
            list.forEach ( rateEntity -> {
                iKingBaseRateService.update ( new UpdateWrapper<KingBaseRateEntity> ().
                        set ( "is_send", KingConstUtil.KING_DATA_IS_SEND_YES ).
                        set ( "update_time", DateUtils.getNowDate () ).
                        eq ( "rate_king_id", rateEntity.getRateKingId () ) );
            } );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "汇率体系推送失败：【" + sb + "】" );
        }
    }


    /**
     * 币别提交
     * @param list
     * @param client
     * @throws Exception
     */
    private void submit (List<KingBaseRateEntity> list, K3CloudApi client) throws Exception {
        RateBo bo = new RateBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( rate -> {
            strings.add ( rate.getRateKingId () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.submit ( KingConstUtil.BD_Rate, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //提交成功
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "汇率体系-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.error ( "{} 提交成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "汇率体系提交失败：【" + sb + "】" );
        }
    }

    /**
     * 审核币别
     * @param list
     * @param client
     * @throws Exception
     */
    private void audit (List<KingBaseRateEntity> list, K3CloudApi client) throws Exception {
        RateBo bo = new RateBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( rate -> {
            strings.add ( rate.getRateKingId () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.audit ( KingConstUtil.BD_Rate, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "汇率体系-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 审核成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "汇率体系审核失败：【" + sb + "】" );
        }
    }

}
